import {defineStore} from "pinia";
import {ref} from "vue";
import {hasPermission} from "@/utils/permission.ts";
import {todoStatus, todoStatusCreate, todoStatusDelete, todoStatusUpdate} from "@/services/api/todo.ts";
import useMessage from "@/utils/useMessage.ts";
import {Modal} from "ant-design-vue";

export const useTodoStatusStore = defineStore('todoStatus', () => {
    const dataSource = ref<StatusType[]>([])
    const loading = ref<boolean>(false)
    const getList = async (force?: boolean) => {
        if (!force && dataSource.value.length > 0) {
            return
        }
        try {
            loading.value = true
            const res: ApiResponse<StatusType[]> = await todoStatus()
            if (res.code === 200) {
                dataSource.value = res.data
            } else {
                useMessage(500, res.message)
            }
        } finally {
            setTimeout(() => loading.value = false, 100)
        }
    }
    const create = async (params: StatusFormType) => {
        if (!hasPermission('admin:todo:create')) return false
        const res = await todoStatusCreate(params)
        if (res.code === 200) {
            await getList(true)
        }
        useMessage(res.code, res.message)
        return res.code === 200
    }
    const update = async (id: number, params: StatusFormType) => {
        if (!hasPermission('admin:todo:update')) return false
        const res = await todoStatusUpdate(id, params)
        if (res.code === 200) {
            const item = dataSource.value.find(a => a.id === id)
            if (item) {
                Object.assign(item, params)
            }
        }
        useMessage(res.code, res.message)
        return res.code === 200
    }
    const remove = async (id: number) => {
        if (!hasPermission('admin:todo:delete')) return false
        Modal.confirm({
            title: '删除确认',
            content: '确定要删除吗？',
            onOk: async () => {
                const res = await todoStatusDelete(id)
                if (res.code === 200) {
                    dataSource.value = dataSource.value.filter(item => item.id !== id)
                }
                useMessage(res.code, res.message)
                return res.code === 200
            }
        });
    }
    return {
        dataSource,
        loading,
        getList,
        create,
        update,
        remove
    }
})